package com.alan.sso.share.utils;

import com.alan.sso.share.bean.SsoUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;

import java.util.Map;
import java.util.concurrent.*;

/**
 * @Auther: Alan liu
 * @Date: 2018/12/21 10:57
 * @Description: SsoSessionStorage
 */
public class SsoSessionStorage {

    private static final int peroid = 30;
    private static final int delay = 1;
    private static SsoSessionStorage ssoSessionStorage = new SsoSessionStorage();
    private Map<Long, SsoUser> userMap = new ConcurrentHashMap();

    private SsoSessionStorage() {
        this.scheduled();
    }

    public static SsoSessionStorage getInstance() {
        return ssoSessionStorage;
    }

    /**
     * @Author Alan liu
     * @Description 设置一个定时，30分钟清除一次用户信息
     * @Date 10:58 2018/12/21
     * @param
     * @return void
     **/
    private void scheduled() {
        ScheduledExecutorService ses = new ScheduledThreadPoolExecutor(1,new BasicThreadFactory.Builder().namingPattern("scheduled-pool-%d").daemon(true).build());
        ses.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                SsoSessionStorage.this.userMap.clear();
            }
        }, 1L, 30L, TimeUnit.MINUTES);
    }

    public void putIfAbsent(SsoUser ssoUser) {
        if (ssoUser != null && this.userMap.get(ssoUser.getId()) == null) {
            this.userMap.put(ssoUser.getId(), ssoUser);
        }
    }

    public SsoUser getSsoUser(Long uid) {
        return uid != null ? (SsoUser)this.userMap.get(uid) : null;
    }

}
